<?php
/**
 * Created by PhpStorm.
 * User: hemingguang
 * Date: 2015/7/28
 * Time: 16:17
 */

class openapi_utils_xmlutil{

    /**
     * 数组转化为xml对象
     * @param $arr 传入数组，对象也可
     * @param int $dom
     * @param int $item
     * @return string
     */
    public function arrtoxml($arr,$dom=0,$item=0){
        if (!$dom){
            $dom = new DOMDocument("1.0");
        }
        if(!$item){
            $item = $dom->createElement("root");
            $dom->appendChild($item);
        }
        if(gettype($arr) == 'Object'){
            $arr = $this->objectToArray($arr);
        }
        foreach ($arr as $key=>$val){
            $itemx = $dom->createElement(is_string($key)?$key:"item");
            $item->appendChild($itemx);
            if (!is_array($val)){
                $text = $dom->createTextNode($val);
                $itemx->appendChild($text);
            }else {
                $this->arrtoxml($val,$dom,$itemx);
            }
        }
        return $dom->saveXML();
    }

    /**
     * 对象转为数组
     * @param $e 传入对象参数
     * @return array|void
     */
    private function objectToArray($e){
        $e=(array)$e;
        foreach($e as $k=>$v){
            if( gettype($v)=='resource' ) return;
            if( gettype($v)=='object' || gettype($v)=='array' )
                $e[$k]=(array)$this->objectToArray($v);
        }
        return $e;
    }

}
